package com.googlecode.recycled.lang.jse.api.net;

import com.google.common.base.Function;
import com.googlecode.recycled.lang.assertions.Assert;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.UnhandledException;

import javax.annotation.Nullable;
import java.io.File;
import java.net.*;

public class Urls {

    // CONSTANTS

    public final static String URL_PREFIX_FILE = "file";

    public final static String URL_PROTOCOL_SUFIX = "://";

    // CONSTRUCTION

    private Urls() {
    }

    // CONVERTERS

    public static URL asUrl(String url) {
        Assert.notBlank(url);

        try {
            return new URL(url);
        } catch (MalformedURLException e) {
            throw new UnhandledException(e);
        }
    }

    public static File asFile(URL url) {
        Assert.notNull(url);

        try {
            return new File(url.toURI());
        } catch (URISyntaxException e) {
            return new File(url.getPath());
        }
    }

    public static URL asFileUrl(String path) {
        Assert.notBlank(path);

        try {
            return new URL(URL_PREFIX_FILE + URL_PROTOCOL_SUFIX + path);
        } catch (MalformedURLException e) {
            throw new UnhandledException(e);
        }
    }

    public static InetAddress asInetAddress(@Nullable String address) {
        return FUNCTION_STRING_TO_INETADDRESS.apply(address);
    }

    // FUNCTIONS

    public static final Function<String, InetAddress> FUNCTION_STRING_TO_INETADDRESS = new Function<String, InetAddress>() {
        @Override
        public InetAddress apply(@Nullable String address) {
            if (StringUtils.isBlank(address)) {
                return null;
            }
            try {
                return InetAddress.getByName(address);
            } catch (UnknownHostException e) {
                throw new UnhandledException(e);
            }
        }

    };

}
